package com.ant.storage.wechat;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ant.storage.common.ResultCode;
import com.ant.storage.handler.AntException;
import com.ant.storage.pojo.InvoiceInfo;
import com.ant.storage.utils.DateFormat;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author hzd
 * @version 1.0
 * @date 2024/3/18 10:56
 */
public class WeChatUtils {

    /**
     * 获取企业微信token
     *
     * @param corpid
     * @param corpsecret
     * @return
     */
    public static String gettoken(String corpid, String corpsecret) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret;
        String data = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(data);
        return jsonObject.getString("access_token");
    }

    /**
     * 上传临时素材文件
     *
     * @param type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件（file）
     * @return
     */
    public static String upload(String type, String path, File file) {
        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + gettoken(WeChatConstants.CORPID,
                        WeChatConstants.CORPSECRET) + "&type=" + type;
        Map<String, Object> map = new HashMap<>();
        if (file == null) {
            file = FileUtil.file(path);
        }
        map.put("media", file);
        String post = HttpUtil.post(url, map);
        return post;
    }

    /**
     * 提交审批申请
     *
     * @return
     */
    public static String applyeventInfo(Applyevent applyevent) {
        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/oa/applyevent?access_token=" + gettoken(WeChatConstants.CORPID,
                        WeChatConstants.CORPSECRET);
        String post = HttpUtil.post(url, JSON.toJSONString(applyevent), 60000);
        return post;
    }

    /**
     * @param template_id 模板的唯一标识id
     * @return
     */
    public static String gettemplatedetail(String template_id) {
        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/oa/gettemplatedetail?access_token=" + gettoken(WeChatConstants.CORPID, WeChatConstants.CORPSECRET);
        Map<String, Object> map = new HashMap<>();
        map.put("template_id", template_id);
        String post = HttpUtil.post(url, JSON.toJSONString(map));
        return post;
    }


    /**
     * 获取审批申请详情
     *
     * @param sp_no 审批单编号。
     * @return
     */
    public static String getapprovaldetail(String sp_no) {
        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovaldetail?access_token=" + gettoken(WeChatConstants.CORPID, WeChatConstants.CORPSECRET);
        Map<String, Object> map = new HashMap<>();
        map.put("sp_no", sp_no);
        String post = HttpUtil.post(url, JSON.toJSONString(map));
        return post;
    }

    /**
     * 获取部门列表
     *
     * @return
     */
    public static List<String> departmentList() {
        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + gettoken(WeChatConstants.CORPID
                        , WeChatConstants.CORPSECRET);
        String post = HttpUtil.get(url);
        JSONObject jsonObject = JSONObject.parseObject(post);
        String errcode = jsonObject.getString("errcode");
        if (StringUtils.isNotBlank(errcode) && errcode.equals("0")) {
            JSONArray department = jsonObject.getJSONArray("department");
            List<String> departmentList = new ArrayList<>();
            for (int i = 0; i < department.size(); i++) {
                JSONObject data = department.getJSONObject(i);
                departmentList.add(data.getString("id"));
            }
            return departmentList;
        } else {
            return null;
        }
    }

    /**
     * 获取部门成员
     */
    public static String simplelist(String department_id) {
        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + gettoken(WeChatConstants.CORPID
                        , WeChatConstants.CORPSECRET);
        Map<String, Object> map = new HashMap<>();
        map.put("department_id", department_id);
        return HttpUtil.get(url, map);
    }

    /**
     * 手机号获取userid
     */
    public static String getuserid(String mobile) {
        String url =
                "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=" + gettoken(WeChatConstants.CORPID,
                        WeChatConstants.CORPSECRET);
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", mobile);
        String post = HttpUtil.post(url, JSON.toJSONString(map));
        JSONObject jsonObject = JSONObject.parseObject(post);
        String errcode = jsonObject.getString("errcode");
        if (StringUtils.isNotBlank(errcode) && errcode.equals("0")) {
            return jsonObject.getString("userid");
        }
        return null;
    }

    /**
     * MultipartFile转File
     */
    public static File transferToFile(MultipartFile multipartFile) {
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1] + ".");
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 获取企业微信所有人员
     *
     * @return
     */
    public static List<StaffVo> getUserList() {
        List<String> stringList = departmentList();
        List<StaffVo> staffVos = new ArrayList<>();
        for (String data : stringList) {
            String simplelist = simplelist(data);
            JSONObject jsonObject = JSONObject.parseObject(simplelist);
            String errcode = jsonObject.getString("errcode");
            if (StringUtils.isNotBlank(errcode) && errcode.equals("0")) {
                JSONArray userlist = jsonObject.getJSONArray("userlist");
                for (int i = 0; i < userlist.size(); i++) {
                    JSONObject user = userlist.getJSONObject(i);
                    String name = user.getString("name");
                    String userid = user.getString("userid");
                    if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(userid)) {
                        StaffVo staffVo = new StaffVo();
                        staffVo.setUserId(userid);
                        staffVo.setUserName(name);
                        staffVos.add(staffVo);
                    }
                }
            }
        }
        return staffVos;
    }


    public static String launchWeChatData(InvoiceInfo info) throws Exception {
        String weChat = info.getWeChat();
        if (StringUtils.isEmpty(weChat)) {
            throw new AntException(ResultCode.FAILURE.getResultCode(), info.getUserName() + "未绑定企业微信");
        }
        Applyevent applyevent = new Applyevent();
        applyevent.setCreator_userid(weChat);
        //审批模板id
        applyevent.setTemplate_id(WeChatConstants.TEMPLATE_ID);
        //审核人
        if (info.getApproval() == null || info.getApproval().size() == 0) {
            throw new AntException("请选择审批人");
        }
        List<Approver> approverList = new ArrayList<>();
        for (String data : info.getApproval()) {
            Approver approver = new Approver();
            approver.setUserid(Arrays.asList(data));
            approverList.add(approver);
        }
        applyevent.setApprover(approverList);
        BigDecimal money = info.getInvoicePrice().setScale(2, BigDecimal.ROUND_HALF_UP);
        //抄送人
        if (info.getNotify() == null || info.getNotify().size() == 0) {
            throw new AntException("请选择抄送人");
        }
        applyevent.setNotifyer(info.getNotify());
        String reimbursementName = info.getReimbursementTypeText();
        applyevent.setApplyDataContents(
                applyevent.controlText("Text-1710743560114", info.getInvoiceName()),
                applyevent.controlDate("Date-1710743598261", "day", DateFormat.getCurrentDates(info.getStartTime())),
                applyevent.controlDate("Date-1710924172855", "day", DateFormat.getCurrentDates(info.getEndTime())),
                applyevent.controlSelector("Selector-1710743676914", "single", selectorType(info.getAccountUrgency())),
                applyevent.controlTable("Table-1710743739997", info.getDetailList()),
                applyevent.controlMoney("Money-1710743798066", money.toString()),
                applyevent.controlText("Textarea-1710743996304", info.getInvoiceNotes()),
                applyevent.controlText("Text-1710743809992", info.getAccountName()),
                applyevent.controlText("Text-1710743821573", info.getAccountBank()),
                applyevent.controlText("Text-1710743836477", info.getAccountNumber()),
                applyevent.controlFile("File-1710743911829", info.getAnnexs()),
                applyevent.controlFile("File-1710743980381", info.getMediaId())
        );
        //摘要
        applyevent.setSummaryInfo("申请人: " + info.getUserName(), "类型: " + reimbursementName, "金额: " + money + "元");
        String str = JSON.toJSONString(applyevent);
      //  System.out.println(str);
       // return "202404170012";
        String data = WeChatUtils.applyeventInfo(applyevent);
        JSONObject jsonObject = JSONObject.parseObject(data);
        String errcode = jsonObject.getString("errcode");
        // System.out.println(jsonObject);
        if (StringUtils.isNotEmpty(errcode) && errcode.equals("0")) {
            return jsonObject.getString("sp_no");
        } else {
            String errmsg = jsonObject.getString("errmsg");
            throw new AntException(errmsg);
        }
    }

    public static String selectorType(String type) {
        if (type == null) {
            return "option-1710743715210";
        }
        if (type.equals("2小时完成")) {
            return "option-1710743676914";
        } else if (type.equals("4小时完成")) {
            return "option-1710743676915";
        } else if (type.equals("24小时完成")) {
            return "option-1710743715210";
        } else if (type.equals("48小时完成")) {
            return "option-1710743720741";
        } else if (type.equals("27小时完成")) {
            return "option-1710743724693";
        } else {
            return "option-1710743715210";
        }
    }

    public static List<Files> uploads(String type, List<String> paths, File file) {
        List<Files> filesList = new ArrayList<>();
        String returnFileUrl = null;
        if (type == "1") {
            for (String data : paths) {
                returnFileUrl = WeChatUtils.upload("image", data, null);
            }
        } else {
            returnFileUrl = WeChatUtils.upload("file", null, file);
        }
        JSONObject jsonObject = new JSONObject(Boolean.parseBoolean(returnFileUrl));
        String errcode = jsonObject.getString("errcode");
        if (StringUtils.isNotEmpty(errcode) && errcode.equals("0")) {
            String media_id = jsonObject.getString("media_id");
            Files files = new Files();
            files.setFile_id(media_id);
            filesList.add(files);
        } else {
         //   System.out.println(jsonObject);
            String errmsg = jsonObject.getString("errmsg");
            throw new AntException(errmsg);
        }
        return filesList;
    }


    public static Contents getContents(String id, String valueText, List<String> paths, File file, String control,
                                       String titlesText) {
        Contents contents = new Contents();
        Values value = new Values();
        control = control == null ? "Text" : control;
        titlesText = titlesText == null ? "文本控件" : titlesText;
        contents.setId(id);
        if ((paths != null && paths.size() > 0) || file != null) {
            control = "File";
            titlesText = "附件";
            List<Files> filesList = new ArrayList<>();
            if (file != null) {
                String returnFileUrl = WeChatUtils.upload("file", null, file);
                JSONObject jsonObject = JSONObject.parseObject(returnFileUrl);
                String errcode = jsonObject.getString("errcode");
                if (StringUtils.isNotEmpty(errcode) && errcode.equals("0")) {
                    String media_id = jsonObject.getString("media_id");
                    Files files = new Files();
                    files.setFile_id(media_id);
                    filesList.add(files);
                } else {
                    String errmsg = jsonObject.getString("errmsg");
                    throw new AntException(errmsg);
                }
            } else {
                for (String data : paths) {
                    String image = WeChatUtils.upload("image", data, null);
                    JSONObject jsonObject = JSONObject.parseObject(image);
                    String errcode = jsonObject.getString("errcode");
                    if (StringUtils.isNotEmpty(errcode) && errcode.equals("0")) {
                        String media_id = jsonObject.getString("media_id");
                        Files files = new Files();
                        files.setFile_id(media_id);
                        filesList.add(files);
                    } else {
                        String errmsg = jsonObject.getString("errmsg");
                        throw new AntException(errmsg);
                    }
                }
            }
            value.setFiles(filesList);
        }
        Titles titles = new Titles();
        titles.setText(titlesText);
        contents.setControl(control);
        contents.setTitle(Arrays.asList(titles));
        if (control.equals("Money")) {
            value.setNew_money(valueText);
        } else {
            value.setText(valueText);
        }
        contents.setValue(value);
        if (StringUtils.isNotEmpty(valueText) || (paths != null && paths.size() > 0) || file != null) {
            return contents;
        } else {
            return null;
        }
    }

//    public static void main(String[] args) throws IOException, ParseException {
//        String qq = gettemplatedetail("3WLuFTTgL1MQMi8ftRa3MaVhfWeL81gAnB4N3gn3");
//        System.out.println(qq);
//        String s = selectorType("4小时完成");
//        System.out.println(s);
        //  String str = upload("image", "http://182.140.221.205:9999/storageApi/pic/d2a33b3e3c504d9b8eff50dc4d981a48.jpg",null);
        //  System.out.println(str);
        //        System.out.println(getapprovaldetail("202403110025"));
        //        System.out.println( departmentList());
   // }
}
